<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/9/5
 * Time: 17:10
 */

namespace app\bm\controller;


use think\Request;

class Item extends Common
{
    public function index()
    {
        $Categroy = new \app\common\model\Item();
        $category_to_tree = $Categroy->lists();
        $this->assign([
            'category_to_tree'=>$category_to_tree
        ]);
        return $this->view->fetch();
    }

    public function create()
    {
        $Categroy = new \app\common\model\Item();
        $category_to_tree = $Categroy->lists();
        $this->assign([
            'category_to_tree'=>$category_to_tree
        ]);
        return $this->view->fetch();
    }

    public function save(Request $request)
    {
        if($request->isPost()){
            $res = \app\common\model\Item::create($request->post());
            if($res){
                return $this->success("添加成功");
            }
        }else{
            return $this->error('非法请求');
        }
    }

    public function edit($id='')
    {
        if($id){
            $Category = new \app\common\model\Item();
            $info = $Category->info($id);
            if($info){
                // 获取分类
                $category_to_tree = $Category->lists();

                $this->assign([
                    'info'=>$info,
                    'category_to_tree'=>$category_to_tree
                ]);
                return $this->view->fetch();
            }else{
                return $this->error('数据请求失败，请核对请求参数');
            }
        }else{
            return $this->error('参数错误');
        }
    }

    public function update(Request $request)
    {
        if($request->isPost()){
            $res = \app\common\model\Item::update($request->post());
            if($res){
                return $this->success("修改成功");
            }
        }else{
            return $this->error('非法请求');
        }
    }

    public function delete()
    {
        if(empty($id)){
            return $this->error('参数错误!');
        }

        //判断该分类下有没有子分类，有则不允许删除
        $child = Db::name('Item')->where(array('upid'=>$id,'c_id'=>UID))->field('id')->select();
        if(!empty($child)){
            return $this->error('请先删除该分类下的子分类');
        }

        //判断该分类下有没有内容
        $goods_list = Db::name('Goods')->where(array('type_id'=>$id,'c_id'=>UID))->field('id')->select();
        if(!empty($goods_list)){
            return $this->error('请先删除该分类下的商品（包含回收站）');
        }

        $res = Db::name('Item')->delete($id);

        if($res !== false){
            return $this->success('删除分类成功！');
        }else{
            return $this->error('删除分类失败！');
        }
    }
}